#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Datetime: 2020/12/18 下午7:34
# @Author  : HUANG Xiong
# @Site    : 
# @File    : common_tools.py
# @Software: PyCharm 

"""
脚本说明：取数API模块的通用函数
"""
import datetime as dt

from quant_researcher.quant.project_tool.db_operator import db_conn, my_mysql
from quant_researcher.quant.project_tool import time_tool


def get_max_date_of_table(date_col_name, table_name, end_date=None,
                          other_filter=None, conn=None, include_equal=True):
    """
    获得一个表中不大于指定日期的最大日期

    :param str date_col_name: 需要查询的日期那一列的名称
    :param str table_name: 需要查询的表
    :param str end_date: 日期列过滤条件，若为None，则获取表中的最大日期
    :param list other_filter: 其他过滤条件
    :param pymysql.connections.Connection conn: 数据库连接，若不输入，则默认tk_mfdb_23库
    :param bool include_equal: 输入end_date时是否需要包含end_date这天，默认包含
    :return: 如果表中日期格式为date，转换为带杠字符串；如果为str，直接输出
    """
    tmp_conn = db_conn.get_derivative_data_conn() if conn is None else conn

    where = []
    if end_date is not None:
        compare_sign = '<='
        if not include_equal:
            compare_sign = '<'
        where.append(f"`{date_col_name}` {compare_sign} '{end_date}'")
    if other_filter is not None:
        where = where + other_filter
    df = my_mysql.read_v2(select=f"max({date_col_name}) as end_date",
                          sfrom=table_name,
                          where=where,
                          conn=tmp_conn)
    if conn is None:
        tmp_conn.close()
    max_date = df['end_date'].iloc[0]
    if max_date is not None and isinstance(max_date, dt.date):
        max_date = time_tool.format_date_str(max_date)
    return max_date


if __name__ == '__main__':
    print(get_max_date_of_table('estimated_date', 'mf_di_fndholding_estimated_day',
                                '2021-01-14', include_equal=False))
